﻿using System;
using System.Web;
using System.Threading;
using System.Globalization;
using WebPattern.DataAccess;
using System.Net;

/// <summary>
/// Summary description for Global
/// </summary>
public class Global : HttpApplication
{    
    public Global()
	{
		//
		// TODO: Add constructor logic here
		//
    }

    #region Application Life Cycle
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

        #region log4net
        // log4net.config
        System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath("~/wLog4net.config"));
        if (fi != null && fi.Exists)
        {
            // Code that runs on application startup
            log4net.Config.XmlConfigurator.Configure(fi);
        }

        // web.config
        //log4net.Config.XmlConfigurator.Configure();

        // set properti hostName
        log4net.ThreadContext.Properties["hostName"] = Dns.GetHostName();
        #endregion   
     
        #region NHibernate
        //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
        var factory = NHibernateSessionManager.ConfigureFromFile(Server.MapPath("~/wHibernate.config"));
        #endregion
    }

    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }

    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }

    void Application_BeginRequest(object sender, EventArgs e)
    {        
        NHibernateSessionManager.BindSession();
    }

    void Application_EndRequest(object sender, EventArgs e)
    {
        NHibernateSessionManager.UnbindSession();
    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Session["sessionStart"] = true; // using for Change language bool value
    }

    /// <summary>
    /// This event occurs just before ASP.Net begins executing a handler such as a page or a web service.
    /// At this point, the session state is available. 
    /// </summary>
    void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        try
        {
            if (Session != null)
            {
                if (Session["sessionStart"] != null && Convert.ToBoolean(Session["sessionStart"]))
                {
                    Session["__isLanguageChanging"] = true;
                    Session.Remove("sessionStart");
                    Session["__currentLanguage"] = Thread.CurrentThread.CurrentCulture.Name;
                }
                else
                {
                    Session["__isLanguageChanging"] = false;
                    if (Session["__currentLanguage"] != null)
                    {
                        CultureInfo ci = new CultureInfo(Session["__currentLanguage"].ToString());
                        Thread.CurrentThread.CurrentCulture = ci;
                        Thread.CurrentThread.CurrentUICulture = ci;
                    }
                }

                if (Request.Form.Keys.Count > 0)
                {
                    foreach (string key in Request.Form.AllKeys)
                    {
                        if (key.Contains("iBtnLanguage_"))
                        {
                            Session["__isLanguageChanging"] = true;
                            try
                            {
                                string selectedCultureName = GetCultureNameFromIdImage(key);

                                if (Session["__currentLanguage"] != null && Session["__currentLanguage"].ToString() == selectedCultureName)
                                    Session["__isLanguageChanging"] = false;
                                else
                                    Session["__currentLanguage"] = selectedCultureName;

                                CultureInfo ci = new CultureInfo(Session["__currentLanguage"].ToString());
                                Thread.CurrentThread.CurrentCulture = ci;
                                Thread.CurrentThread.CurrentUICulture = ci;
                            }
                            catch (Exception ex) { };
                            break;
                        }
                    }
                }
            }
        }
        catch (Exception ex) { };
    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

    }
    #endregion

    #region Helper Methods
    private string GetCultureNameFromIdImage(string idIBtnLanguage)
    {
        return idIBtnLanguage.Split(new string[] { "iBtnLanguage_" }, StringSplitOptions.RemoveEmptyEntries)[1]
                            .Replace("_", "-")
                            .Replace(".x", "")
                            .Replace(".y", "");

        // Or do Switch
        //switch (idIBtnLanguage)
        //{
        //    case "ctl00$iBtnLanguage_ru_RU.x":
        //    case "ctl00$iBtnLanguage_ru_RU.y": return "ru-RU";

        //    case "ctl00$iBtnLanguage_en_GB.x":
        //    case "ctl00$iBtnLanguage_en_GB.y": return "en_GB";

        //    case "ctl00$iBtnLanguage_ro_RO.x":
        //    case "ctl00$iBtnLanguage_ro_RO.y": return "ro_RO";

        //    default: return Thread.CurrentThread.CurrentCulture.Name;
        //}
    }
    #endregion
}